import React, {forwardRef, ReactNode, useEffect, useState} from 'react';
import {Input, InputProps, Textarea, View} from '@tarojs/components';
import {
  Form,
  Radio,
  RadioGroup,
  Checkbox,
  CheckboxGroup,
  Slider,
  Rate,
  Stepper,
  Uploader,
  DatetimePicker,
  FormItem,
  Switch,
  Icon, Picker,
} from '@antmjs/vantui';
import Utils from "@/utils/common";
import {IFormInstanceAPI} from "@antmjs/vantui/types/form";
import CustomFormLabel from "@/components/CustomFormLabel";
import './dynamic_form.less';


// 表单配置类型
export interface OptionConfig {
  label: string;
  text?: string;
  id?: string;
  value: string | number;
  disabled?: boolean;
}

export interface FormConfig {
  type: string;
  name: string;
  label: string;
  placeholder?: string;
  layout?: 'vertical' | 'horizontal'
  options?: Array<OptionConfig>;
  required?: boolean;
  rules?: any[];
  maxlength?: number;
  minHeight?: string;
  renderReactNode?: () => ReactNode
  renderRight?: () => ReactNode
  showWordLimit?: boolean;
  disabled?: boolean;
  password?: boolean
  min?: number;
  max?: number;
  step?: number;
  count?: number;
  isHideItem?: boolean | undefined;
  inputBgColor?: string;
  padding?: string;
  inputType?: keyof InputProps.Type;
  timeType?: "datetime" | "date" | "year-month" | "time" | undefined;

  [key: string]: any;
}

export interface DynamicFormProps {
  /**
   * Form configuration array
   */
  formConfigs: FormConfig[];
  /**
   * Initial form values
   */
  initialValues?: Record<string, any>;
  form: IFormInstanceAPI
  children?: ReactNode;
}

const DynamicFormV2 = forwardRef<any, DynamicFormProps>((({
                                                            formConfigs,
                                                            form,
                                                            children
                                                          }, ref) => {
  const [, forceUpdate] = useState({});

  const handleFormChange = (key: string, value: any) => {
    forceUpdate({});
  };

  const valueFormatUpload = (event, formName, instance) => {
    Utils.showLoading('上传中...');
    const {file} = event.detail;
    let fileList = instance.getFieldValue(formName) || [];
    fileList = fileList.concat(file);
    // 异步更新
    return new Promise((resolve) => {
      setTimeout(() => {
        Utils.clear();
        resolve(fileList);
      }, 3000);
    });
  };

  const deleteFile = (event, formName) => {
    Utils.showLoading('删除中...');
    const {index, fileList} = event.detail;
    fileList.splice(index, 1);
    handleFormChange(formName, fileList)
    forceUpdate({});
    Utils.clear();
  };
  useEffect(() => {
    console.log('表单初始值:', form.getFieldValue('fileType')); // 应输出 ["0", "1"]
  }, [form]);

  // 渲染动态表单项
  const renderFormItem = (config: FormConfig) => {
    const layout = config.layout || 'horizontal';
    const baseStyles = {
      width: '100%',
      padding: '0',
      '--form-label-width': '100px',
    };

// 2. 根据条件决定变化的样式
    const conditionalStyles = config.layout === "vertical"
      ? {'--form-controll-margin-left': '10PX'}
      : {'--form-controll-margin-left': '20PX'};

// 3. 将基础样式和条件样式合并
    const style = {
      ...baseStyles,
      ...conditionalStyles,
    };


    switch (config.type) {
      case 'input':
        return (
          <FormItem
            name={config.name}
            label={<CustomFormLabel>{config.label}</CustomFormLabel>}
            rules={config.rules}
            required={config.required}
            trigger='onInput'
            validateTrigger='onBlur'
            layout={layout}
            renderRight={config?.renderRight ? config?.renderRight() : null}
            style={style}
            borderBottom
            valueFormat={(e) => e.detail.value}
          >
            <Input
              password={config.password}
              disabled={config.disabled}
              maxlength={config.maxlength}
              type={config.inputType}
              placeholder={config.placeholder}
              style={{
                width: '100%',
                backgroundColor: config.inputBgColor,
                padding: config.padding ? config.padding : '0 5PX'
              }}
            />
          </FormItem>
        );

      case 'textarea':
        return (
          <FormItem
            name={config.name}
            label={<CustomFormLabel>{config.label}</CustomFormLabel>}
            rules={config.rules}
            required={config.required}
            trigger='onInput'
            renderRight={config?.renderRight ? config?.renderRight() : null}
            validateTrigger='onBlur'
            layout={layout}
            style={style}
            borderBottom
            valueFormat={(e) => e.detail.value}
          >
            <Textarea
              placeholder={config.placeholder}
              maxlength={config.maxlength}
              trigger='onInput'
              disabled={config.disabled}
              validateTrigger='onBlur'
              valueFormat={(e) => e.detail.value}
              autoHeight
              style={{
                width: '100%',
                padding: '10px',
                minHeight: config.minHeight ? config.minHeight : '40px',
                lineHeight: 'normal',
                backgroundColor: config.inputBgColor
              }}
            />
          </FormItem>
        );

      case 'radio':
        return (
          <FormItem
            rules={config.rules}
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style} borderBottom
          >
            <RadioGroup
              disabled={config.disabled}
              direction='horizontal'
              value={form.getFieldValue(config.name)}
              style={{display: 'flex', flexWrap: 'wrap', gap: '0px'}}
              onChange={(e) => handleFormChange(config.name, e.detail)}
            >
              {config.options ? config.options.map((option) => {
                // 添加调试日志：检查表单值与 Radio name 是否一致
                const currentValue = form.getFieldValue(config.name);
                const isChecked = currentValue === String(option.value); // 计算是否选中
                console.log(`选项${option.value}匹配状态:`, currentValue === String(option.value));
                return (
                  <Radio
                    className='custom-radio'
                    renderIcon={<View className={`radio-label ${isChecked ? 'radio-label-checked' : ''}`}>
                      {option.label}
                    </View>}
                    key={option.value}
                    name={String(option.value)} // 确保为字符串类型
                    shape='square'
                    disabled={option.disabled}
                  >
                  </Radio>
                );
              }) : <View>无</View>}
            </RadioGroup>
          </FormItem>
        );

      case 'checkbox':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            mutiLevel
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style}
          >
            <CheckboxGroup
              muiltSelect
              disabled={config.disabled}
              direction='horizontal'
              style={{display: 'flex', flexWrap: 'wrap', gap: '10px'}}
            >
              {config.options ? config.options.map((option) => {
                return (
                  <Checkbox key={option.value} name={String(option.value)} shape='square'>
                    {option.label}
                  </Checkbox>
                );
              }) : <View>无</View>}
            </CheckboxGroup>
          </FormItem>
        );

      case 'switch':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style} valueKey='checked'
          >
            <Switch/>
          </FormItem>
        );

      case 'slider':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style}
          >
            <Slider
              activeColor='#07c160'
              min={config.min}
              max={config.max}
              step={config.step}
              style={{width: '90%', margin: '10px'}}
            />
          </FormItem>
        );

      case 'rate':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style}
          >
            <Rate count={config.count}/>
          </FormItem>
        );

      case 'stepper':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            required={config.required}
            name={config.name} label={<CustomFormLabel>{config.label}</CustomFormLabel>} layout={layout}
            style={style}
          >
            <Stepper
              min={config.min}
              max={config.max}
              step={config.step}
            />
          </FormItem>
        );
      case 'render':
        return (
          config.renderReactNode ? config.renderReactNode() : null
        );
      case 'uploader':
        return (
          <FormItem
            borderBottom
            required={config.required}
            name={config.name}
            label={<CustomFormLabel>{config.label}</CustomFormLabel>}
            valueKey='fileList'
            valueFormat={valueFormatUpload}
            trigger='onAfterRead'
            layout={layout}
            style={style}
            validateTrigger='onAfterRead'
            rules={{
              rule: (values, call) => {
                if (!values || !Array.isArray(values)) {
                  return call('');
                }

                values.forEach((item, index) => {
                  if (item && item.size > 0.1 * 1024 * 1024) {
                    return call(`图片(${index + 1})大小不得大于 0.1M`);
                  }
                });
                call('');
              },
            }}
          >
            <Uploader
              maxCount={config.maxCount || 5}
              onDelete={(e) => {
                deleteFile(e, config.name);
              }}
            />
          </FormItem>
        );

      case 'datePicker':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            name={config.name}
            label={<CustomFormLabel>{config.label}</CustomFormLabel>}
            valueFormat={(e) => e.detail.value}
            valueKey='value'
            style={style}
            trigger='onInput'
            layout={layout}
            renderRight={<Icon name='arrow'/>}
          >
            <DatetimePicker
              mode='content'
              type={config.timeType}
            />
          </FormItem>
        );
      case 'picker':
        return (
          <FormItem
            borderBottom
            rules={config.rules}
            valueFormat={(e) => e.detail}
            trigger='onInput'
            label={<CustomFormLabel>{config.label}</CustomFormLabel>}
            name={config.name}
            valueKey='value'
            required={config.required}
            controllFlexEnd
          >
            <Picker
              idKey='value'
              mode='content'
              showToolbar
              title={config.placeholder}
              columns={config.options}
              showArrowRight
            />
          </FormItem>
        );

      default:
        return null;
    }
  };

  return (
    <Form form={form} className='dynamic-form-v2'>
      {formConfigs.map((config) => (
        <React.Fragment key={config.name}>
          {renderFormItem(config)}
        </React.Fragment>
      ))}
      {children}
    </Form>
  );
}));

export default DynamicFormV2;
